import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:example_example/bean/BossBean.dart';
import 'package:example_example/global/Global.dart';
import 'package:example_example/global/GlobalUrl.dart';
import 'package:example_example/pages/person/ChangeCode.dart';
import 'package:example_example/pages/person/Login.dart';
import 'package:example_example/pages/view/HeaderView.dart';
import 'package:example_example/pages/view/LoadingDialog.dart';
import 'package:example_example/services/ScreenAdapter.dart';
import 'package:example_example/services/TLSizeFit.dart';
import 'package:example_example/util/HttpUtil.dart';
import 'package:example_example/util/LogUtil.dart';
import 'package:example_example/util/Storage.dart';
import 'package:example_example/util/ToastUtils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../YColors.dart';

class WebOrderPage extends StatefulWidget {
  WebOrderPage({Key key}) : super(key: key);

  _WebOrderPageState createState() => _WebOrderPageState();
}

class _WebOrderPageState extends State<WebOrderPage> {
  WebViewController _controller;
  String _title = "";
  String url = "";
  bool flagLoading = true;

  String Rid = "";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.initJpush();
    url = GlobalUrl.WEB_ORDER;
    print("web我的待办。。。url:$url");

    this.setCheckInfor();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    TLSizeFit.initialize();
    ScreenAdapter.init(context);
    print("web我的待办。。。build");

    return WillPopScope(
        child: Scaffold(
          // appBar: HeaderView(
          //   title: "我的待办",
          //   isShowReturnArrow: false,
          // ),
          body: Container(
            color: YColors.orderBackground,
            // padding: EdgeInsets.fromLTRB(
            //     TLSizeFit.setPx(20), TLSizeFit.setPx(20), TLSizeFit.setPx(20), 0),
            child: setBodyView(),
          ),
        ),
        onWillPop: _requestPop);
  }

  Widget setBodyView() {
    return Stack(
      children: <Widget>[
        SafeArea(
          child: WebView(
            // initialUrl: "https://flutterchina.club/",
            // initialUrl: "https://www.baidu.com/",
            initialUrl: url,
//          initialUrl: GlobalUrl.HELP,
//          initialUrl: _setWebviewUrl(),
//             initialUrl: url,
//                initialUrl: "file:assets/images/files/dist/index.html",
            //JS执行模式 是否允许JS执行
            onPageStarted: (String url) {
              print('onPageStarted 开始: $url');
            },
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (WebViewController controller) {
              print("onWebViewCreated 创建");
              _controller = controller;
              _controller.clearCache(); // 去掉缓存  防止标题重复
            },

            onProgress: (int progress) {
              print("WebView is loading (progress : $progress%)");
              if (progress == 100) {
                setState(() {
                  flagLoading = false;
                });
              }
            },

            onPageFinished: (url) {
              print('onPageFinished: 完成');

              setlocalStorage();
              _controller.evaluateJavascript("document.title").then((result) {
                print('onPageFinished。。。title:$result');
                if (result != "") {
                  setState(() {
                    _title = result;
                  });
                }
              });
            },
            navigationDelegate: (NavigationRequest request) {
              print("即将打开 ${request.url}");
              if (request.url.startsWith("myapp://")) {
                return NavigationDecision.prevent;
              }
              return NavigationDecision.navigate;
            },
            javascriptChannels: <JavascriptChannel>[
              JavascriptChannel(
                  name: "NativeMessage",
                  onMessageReceived: (JavascriptMessage message) {
                    print("参数： ${message.message}");
                    httpJPushloginOut();

                    // if(message.message =='LOGOUT'){
                    //   Navigator.pushNamed(context, "/LoginPage");
                    // }
                  }),
              //   https://www.jianshu.com/p/d9327b3c2b29 Flutter js 相互（调用）通信
//                https://www.jianshu.com/p/86916cab2cf3  Flutter 中 WebView 的使用以及与 JS 交互
              JavascriptChannel(
                  name: "messageBack",
                  onMessageReceived: (JavascriptMessage message) {
                    // print("收到了方法，去返回");
                    //  print("收到了方法，去返回:${message.message}");
                    // print(message.message);   // 我来自js调用sendMessage，我调用了Flutter中的功能
                    // Navigator.of(context).pop("refresh");
                    //    _controller?.evaluateJavascript("showMessage ('我（Flutter）收到了你的消息[${message.message}].)");
                  }),
            ].toSet(),
          ),
        ),
        flagLoading ? LoadingDialog(text: "努力加载中") : Container(),
      ],
    );
  }


  Future<bool> _requestPop() {
    print("POP");
    _controller.canGoBack().then((value) {
      LogUtil.v("物理返回canGoBack:$value");
      if (value) {
        _controller.goBack();
      }else {
        SystemNavigator.pop();
      }
    });
    // if (Navigator.canPop(context)) {
    //   Navigator.pop(context);
    // } else {
    //   SystemNavigator.pop();
    // }
    return Future.value(false);
//  原文链接：https://blog.csdn.net/K_Hello/article/details/108367622
  }

  initJpush() async {
    LogUtil.v("初始化极光推送的功能");
    var id = await Storage.getId(); //注意必须要用 await来修饰
    LogUtil.v("获取登录的id:$id");

    JPush jpush = new JPush();
    //获取注册的id
    jpush.getRegistrationID().then((rid) {
      print("获取注册的RegistrationID:$rid");

      httpJPushRegistrationID(rid);
    });

    //初始化
//    插件版本 >= 0.0.8 android 端支持在 setup 方法中动态设置 channel，动态设置的 channel 优先级比 manifestPlaceholders 中的 JPUSH_CHANNEL 优先级要高。
    jpush.setup(
      appKey: "5d3f34bc7315e47e68864935",
      channel: "theChannel",
      production: false,
      debug: true, // 设置是否打印 debug 日志
    );

    //设置别名  实现指定用户推送
//    jpush.setAlias(id).then((map) {
////      print("设置别名成功了哈222：$id");
////      ToastUtils.toast("设置别名成功");
////      ToastUtils.toast("设置别名成功了哈222：$id");
//    });

//    申请推送权限，注意这个方法只会向用户弹出一次推送权限请求（如果用户不同意，之后只能用户到设置页面里面勾选相应权限），需要开发者选择合适的时机调用。
    jpush.applyPushAuthority(
        new NotificationSettingsIOS(sound: true, alert: true, badge: true));

    jpush.setup(
      debug: false, // 设置是否打印 debug 日志
    );

    try {
      //监听消息通知
      jpush.addEventHandler(
        // 接收通知回调方法。
        onReceiveNotification: (Map<String, dynamic> message) async {
          print("flutter onReceiveNotification: $message");
        },
        // 点击通知回调方法。
        onOpenNotification: (Map<String, dynamic> message) async {
          print("flutter onOpenNotification: $message");
        },
        // 接收自定义消息回调方法。
        onReceiveMessage: (Map<String, dynamic> message) async {
          print("flutter onReceiveMessage: $message");
        },
      );
    } catch (e) {
      print('极光sdk配置异常');
    }
  }

  /**
   * 给后台提交极光的注册id
   */
  httpJPushRegistrationID(registId) async {
    setState(() {
      Rid = registId;
    });
    Storage.setString(Global.JPUSHREGISTERID, registId);

    String registState = await Storage.getString(Global.JPUSHREGISTERSTATE);
    LogUtil.v("极光registState:$registState");

    if (registState != null && registState == "1") {
      LogUtil.v("极光已注册过，不需要再次注册");
      return;
    }

    String url = GlobalUrl.JPUSHUPDATEBINDSTATUS;
    var map = {
      "registrationId": registId,
      "validFlag": "1", //1 登录 0 退出
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.post(url, context: this.context, data: map, headers: mapHeaders,
        success: (data) {
      LogUtil.v("极光的注册success:$data");
//          极光的注册success:{code: 200, success: true, data: null, msg: 操作成功}
      var jsonMap = BossBean.fromJson(data);
      String result = jsonMap.code;
      String message = jsonMap.msg;
      bool success = jsonMap.success;
      if (success) {
        Storage.setString(Global.JPUSHREGISTERSTATE, "1");
      } else {
        ToastUtils.toast(message);
      }
//          ToastUtils.toast(message);
    }, error: (error) {
      LogUtil.v("极光的注册error:$error");
    });
  }

  /**
   * 给后台提交极光的注册id
   */
  httpJPushloginOut() async {
    String registId = await Storage.getString(Global.JPUSHREGISTERID);

    String url = GlobalUrl.JPUSHUPDATEBINDSTATUS;
    var map = {
      "registrationId": registId,
      "validFlag": "0", //1 登录 0 退出
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.post(url, context: this.context, data: map, headers: mapHeaders,
        success: (data) {
      LogUtil.v("极光的注册success:$data");
//          极光的注册success:{code: 200, success: true, data: null, msg: 操作成功}
      var jsonMap = BossBean.fromJson(data);
      String result = jsonMap.code;
      String message = jsonMap.msg;
      bool success = jsonMap.success;
      if (success) {
        Storage.setString(Global.JPUSHREGISTERSTATE, "");
        logoutHttp();
      } else {
        ToastUtils.toast(message);
      }
    }, error: (error) {
      LogUtil.v("极光的注册error:$error");
    });
  }

  /**
   * 退出登录
   */
  logoutHttp() async {
    String url = GlobalUrl.LOGOUTURL;
    var map = {"": ""};
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };

    HttpUtil.delete(url, data: map, headers: mapHeaders, success: (data) {
      print("退出了登录了");
//          接口的数据：{code: 200, success: true, data: null, msg: 注销成功}
      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
      if (success == true) {
//        JPush jpush = new JPush();
//        jpush.deleteAlias();  // 删除别名
        Storage.clear(); // 清除数据
        //跳转并关闭当前页面
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(builder: (context) => new LoginPage()),
          (route) => route == null,
        );
      }
      ToastUtils.toast(message);
    }, error: (errorMsg) {});
  }

  setCheckInfor() async {
    String id = await Storage.getId();
    String apiUrlhttp = GlobalUrl.CHECKPASSWORD + "?id=" + id;
//    var map = {
//      "id": id,
//    };
    var access_token = await Storage.getToken();
    // LogUtil.v("进来了access_token:" + access_token);

    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    var dio = Dio();

    dio.options.headers.addAll(mapHeaders); // 添加headers,如需设置统一的headers信息也可在此添加
    Response response = await dio.get(apiUrlhttp);
    LogUtil.v("进来了data:" + response.data.toString());
//       var str = json.encode(response.data);
    var jsonMap = BossBean.fromJson(response.data);
    String result = jsonMap.code;
    String message = jsonMap.msg;
    bool success = jsonMap.success;
    var getData = jsonMap.data;
    LogUtil.v("进来了getData:" + getData);

    if (success) {
      if (getData != null && getData == "1") {
        LogUtil.v("不用任何操作。。");
      } else {
//    传入用户id，返回状态值：1正常；21默认密码未修改；22密码过期；
        LogUtil.v("去修改密码。。");
//        if (getData == 21) {
//          ToastUtils.toast("默认密码未修改,请修改密码");
//        } else if (getData == 22) {
//          ToastUtils.toast("密码过期,请修改密码");
//        }
//        Navigator.pop(context);
//        Navigator.pushNamed(
//            context, "/ChangeCodePage",arguments: {Global.FLAG: "force",Global.CHANGECODESTATE: getData}); //, arguments: {Global.FLAG: "111"}

        Map arguments = {Global.FLAG: "force", Global.CHANGECODESTATE: getData};
        Navigator.pushAndRemoveUntil(
          context,
          new MaterialPageRoute(
              builder: (context) => new ChangeCodePage(arguments: arguments)),
          (route) => route == null,
        );
      }
//      Navigator.pop(context);
//      Navigator.pushNamed(
//          context, "/ChangeCodePage",arguments: {Global.FLAG: "force"});

    } else {
      ToastUtils.toast(message);
    }
  }

  /*写入token到localStorage*/
//    原文链接：https://blog.csdn.net/Emperor_huanzi/article/details/109218249
  setlocalStorage() async {
    //
    // 需要修改 确认
    String access_token = await Storage.getToken(); //
    access_token = access_token.substring(7, access_token.length);
    // print("设置缓存。。。access_token:${access_token}");
    if (access_token != null) {
      print("设置缓存。。。3333");
      var dictionary = await Storage.getString(Global.DICTIONARY);
      print("获取字典表....:$dictionary");
      if (dictionary != null && dictionary != '') {
        String scriptDictionary = "GetSysDic('$dictionary')";
        _controller.evaluateJavascript(scriptDictionary).then((result) {
          print("设置缓存成功了.字典表成功...:$result");
        });
      }

      var loginInfor = await Storage.getString(Global.LOGINDATA);
      LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
      // LogUtil.v("有缓存loginInfor:$loginInfor");
      // var logBean = json.decode(loginInfor); // Json 字符串转化成 Map 类型
      if (loginInfor != null && loginInfor != '') {
        String scriptDictionary = "GetAppInfo('$loginInfor')";
        _controller.evaluateJavascript(scriptDictionary).then((result) {
          print("设置缓存成功了.用户信息...:$result");
        });
      }
    }
  }
}
